package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.domain.Room;
import com.zzyl.nursing.mapper.RoomMapper;
import com.zzyl.nursing.service.IRoomService;
import com.zzyl.nursing.vo.BedVo;
import com.zzyl.nursing.vo.DeviceInfo;
import com.zzyl.nursing.vo.RoomVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 房间Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-26
 */
@Slf4j
@Service
public class RoomServiceImpl extends ServiceImpl<RoomMapper, Room> implements IRoomService {
    @Autowired
    private RoomMapper roomMapper;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    /**
     * 查询房间
     *
     * @param id 房间主键
     * @return 房间
     */
    @Override
    public Room selectRoomById(Long id) {
        return getById(id);
    }

    /**
     * 查询房间列表
     *
     * @param room 房间
     * @return 房间
     */
    @Override
    public List<Room> selectRoomList(Room room) {
        return roomMapper.selectRoomList(room);
    }

    /**
     * 新增房间
     *
     * @param room 房间
     * @return 结果
     */
    @Override
    public int insertRoom(Room room) {
        return save(room) ? 1 : 0;
    }

    /**
     * 修改房间
     *
     * @param room 房间
     * @return 结果
     */
    @Override
    public int updateRoom(Room room) {
        return updateById(room) ? 1 : 0;
    }

    /**
     * 批量删除房间
     *
     * @param ids 需要删除的房间主键
     * @return 结果
     */
    @Override
    public int deleteRoomByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 根据楼层 id 获取房间视图对象列表
     *
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsByFloorId(Long floorId) {
        return roomMapper.selectByFloorId(floorId);
    }


    /**
     * 获取所有房间（负责老人）
     *
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsWithNurByFloorId(Long floorId) {
        return roomMapper.selectByFloorIdWithNur(floorId);
    }

    @Override
    public RoomVo one(Long id) {
        return roomMapper.one(id);
    }

    /**
     * 获取指定楼层中所有有智能设备的房间信息
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsWithDeviceByFloorId(Long floorId) {
        // 查询有智能设备的房间信息，包含智能设备的信息
        List<RoomVo> roomlist = roomMapper.getRoomsWithDeviceByFloorId(floorId);
        if (ObjectUtil.isNotEmpty(roomlist)) {
            roomlist.forEach(roomVo -> {
                // 遍历出每一个房间的所有设备信息
                List<DeviceInfo> deviceInfoList = roomVo.getDeviceVos();
                if (ObjectUtil.isNotEmpty(deviceInfoList)) {
                    deviceInfoList.forEach(deviceInfo -> {
                        // 遍历出每一个设备，将从redis中获取的数据保存到设备信息中
                        Object rawJson = redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_LAST_DATA, deviceInfo.getIotId());

                        String jsonStr;
                        if (rawJson instanceof String) {
                            jsonStr = (String) rawJson;
                        } else if (rawJson != null) {
                            // 如果是 JSONArray 或其他 JSON 对象，转成字符串
                            jsonStr = JSONUtil.toJsonStr(rawJson);
                        } else {
                            // 数据为空时直接跳过处理
                            return;
                        }

                        deviceInfo.setDeviceDataVos(JSONUtil.toList(jsonStr, DeviceData.class));
                    });
                }

                // 遍历房间中床位
                List<BedVo> bedVoList = roomVo.getBedVoList();
                if (ObjectUtil.isNotEmpty(bedVoList)) {
                    bedVoList.forEach(bedVo -> {
                        List<DeviceInfo> deviceVos = bedVo.getDeviceVos();
                        if (ObjectUtil.isNotEmpty(deviceVos)) {
                            deviceVos
                                    // 遍历床位上的设备，为每个设备，从redis中获取数据保存到设备信息中
                                    .forEach(deviceInfo -> {
                                        // 遍历出每一个设备，将从redis中获取的数据保存到设备信息中
                                        Object rawJson = redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_LAST_DATA, deviceInfo.getIotId());

                                        String jsonStr;
                                        if (rawJson instanceof String) {
                                            jsonStr = (String) rawJson;
                                        } else if (rawJson != null) {
                                            // 如果是 JSONArray 或其他 JSON 对象，转成字符串
                                            jsonStr = JSONUtil.toJsonStr(rawJson);
                                        } else {
                                            // 数据为空时直接跳过处理
                                            return;
                                        }

                                        deviceInfo.setDeviceDataVos(JSONUtil.toList(jsonStr, DeviceData.class));
                                    });
                        }
                    });
                }
            });
        }
        return roomlist;
    }

}
